package org.feng.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import org.feng.entity.CustomDict;

import java.util.*;
import java.util.function.BiConsumer;

/**
 * 字典工具类
 *
 * @author feng
 */
public class DictUtil {

    public static List<Tree<Long>> convertToTree(List<CustomDict> customDictList, Long rootId, BiConsumer<Map<String, Object>, CustomDict> biConsumer) {
        if (CollUtil.isEmpty(customDictList)) {
            return Collections.emptyList();
        }

        List<TreeNode<Long>> treeNodes = new ArrayList<>();
        for (CustomDict customDict : customDictList) {
            TreeNode<Long> treeNode = new TreeNode<>();
            treeNode.setId(customDict.getId());
            treeNode.setName(customDict.getName());
            treeNode.setParentId(customDict.getParentId());
            treeNode.setWeight(customDict.getWeight());
            Map<String, Object> extra = new LinkedHashMap<>();
            extra.put("dictKey", customDict.getDictKey());
            extra.put("dictVal", customDict.getDictVal());
            extra.put("status", customDict.getStatus().getValue());
            extra.put("createUser", customDict.getCreateUser());
            extra.put("createUsername", customDict.getCreateUsername());
            extra.put("createTime", customDict.getCreateTime());
            extra.put("updateTime", customDict.getUpdateTime());
            if (customDict.hasSystemOperation()) {
                extra.put("systemCode", customDict.getSystemCode());
                extra.put("subSystemCode", customDict.getSubSystemCode());
            }
            if (biConsumer != null) {
                biConsumer.accept(extra, customDict);
            }
            treeNode.setExtra(extra);
            treeNodes.add(treeNode);
        }

        return TreeUtil.build(treeNodes, rootId);
    }

    public static List<Tree<Long>> convertToTree(List<CustomDict> customDictList) {
        return convertToTree(customDictList, 0L, null);
    }
}
